import {queryOrderList} from "@src/api/mall/order";
import router from "@src/router";

Component({
  behaviors: [router.routerBehavior],
  options: {
    addGlobalClass: true
  },
  data: {
    loading: false,
    hasNextPage: false,
    pageNum: 0,
    pageSize: 10,
    startX: 0,
    startY: 0,
    firstShow: true,
    listData: []
  },
  lifetimes: {
    ready: function () {
      this.fetchData();
    }
  },
  pageLifetimes: {
    // show() {
    //   this.setData({pageNum: 0, pageSize: 10, hasNextPage: true});
    //   this.fetchData();
    // },
  },
  methods: {
    //获取商城数据
    fetchData() {
      let data = {pageNum: this.data.pageNum + 1, pageSize: this.data.pageSize}
      queryOrderList(data).then(res => {
        if (this.data.pageNum + 1 !== data.pageNum) {
          // 数据已被改变
          return;
        }
        if (res.code === 0) {
          this.setData({loading: false, pageNum: data.pageNum})
          let list = res.data.list;

          list.forEach(val => {
            if (val.items) {
              val.items.forEach(item => {
                if (typeof (item.skuInfo) == 'string') {
                  item.skuInfo = JSON.parse(item.skuInfo)
                }
              })
            }
          });
          let listData = this.data.listData
          if (data.pageNum === 1) {
            listData = []
          }
          this.setData({hasNextPage: res.data.hasNextPage, listData: listData.concat(list)})
        }
      }).catch(() => {
        this.setData({loading: false})
      })
    },
    //进入订单详情
    handleOrderDetail(e) {
      let orderNo = e.currentTarget.dataset.no
      router.push({
        name: "mall/order-detail",
        params: {
          orderNo: orderNo
        },
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          acceptDataFromOpenedPage: (data) => {
            if (data.data == 'test') {
              this.setData({pageNum: 0, pageSize: 10, hasNextPage: false, listData: []});
              this.fetchData();
            }
          },
        }
      })
    },
    onReachBottom() {
      if (this.data.hasNextPage) {
        this.fetchData();
      }
    },
    onPullDownRefresh() {
      wx.stopPullDownRefresh();
      this.setData({pageNum: 0, pageSize: 10, hasNextPage: true});
      this.fetchData();
    }
  }
});
